<template>
  <view>
    <view class="image-container">
      <!-- 加载中显示进度条 -->
      <view v-if="isImageDownloading" class="download-progress">
        <view class="progress-text">{{ downloadProgress }}%</view>
        <view class="progress-bar">
          <view class="progress-fill" :style="{ width: downloadProgress + '%' }"></view>
        </view>
      </view>
      
      <image 
        :src="currentImage" 
        mode="aspectFill" 
        class="display-image"
        @error="handleImageError"
        @load="handleImageLoad"
      ></image>
    </view>

    <view class="button-group">
      <button 
        class="func-btn" 
        @click="chooseAndDisplayImage"
      >
        选择本地图片
      </button>
      <button 
        class="func-btn" 
        @click="downloadNetworkImage"
      >
        下载网络图片
      </button>
      <button 
        class="func-btn" 
        @click="previewCurrentImage"
        :disabled="!currentImage || isImageDownloading"
      >
        预览图片
      </button>
    </view>

    <!-- 明天天气预报显示区域 -->
    <view class="weather-container">
      <view class="weather-title">明天天气预报</view>
      <view v-if="tomorrowWeather" class="weather-info">
        <view>日期：{{ tomorrowWeather.date }}</view>
        <view>星期：{{ tomorrowWeather.weekday }}</view>
        <view>最高温：{{ tomorrowWeather.high }}℃</view>
        <view>最低温：{{ tomorrowWeather.low }}℃</view>
      </view>
      <view v-if="weatherError" class="weather-error">{{ weatherError }}</view>
      <view v-else-if="!tomorrowWeather" class="weather-loading">加载中...</view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentImage: "/static/moreng052.jpg", 
      defaultImage: "/static/logo.png", 
      imageInfo: null,
      tomorrowWeather: null,
      weatherError: "",
      isImageDownloading: false, 
      downloadProgress: 0, 
      networkImageUrl: "https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg", // 修正后的图片地址
      downloadTask: null 
    };
  },
  onLoad() {
    this.getWeatherForecast();
  },
  onUnload() {

    if (this.downloadTask) {
      this.downloadTask.abort();
      console.log("下载任务已取消");
    }
  },
  methods: {  
    navigateBack() {
      uni.navigateBack({ delta: 1 });
    },

    chooseAndDisplayImage() {
      if (this.isImageDownloading) {
        uni.showToast({ title: "正在下载图片，请稍后", icon: "none" });
        return;
      }
      
      uni.chooseImage({
        count: 1, 
        sourceType: ["album", "camera"], 
        sizeType: ["original", "compressed"],
        success: (res) => {
          const tempPath = res.tempFilePaths[0];
          this.currentImage = tempPath; 
          console.log("选择本地图片成功：", tempPath);
        },
        fail: (err) => {
          console.error("选择本地图片失败：", err);
          uni.showToast({ title: "选择失败", icon: "none" });
        }
      });
    },

    previewCurrentImage() {
      if (!this.currentImage) return;

      uni.previewImage({
        current: this.currentImage, 
        urls: [this.currentImage], 
        success: () => console.log("预览成功"),
        fail: (err) => {
          console.error("预览失败：", err);
          uni.showToast({ title: "预览失败", icon: "none" });
        }
      });
    },

    handleImageError() {
      this.currentImage = this.defaultImage;
      this.isImageDownloading = false;
      this.downloadProgress = 0;
      uni.showToast({ title: "图片加载失败", icon: "none" });
    },

    handleImageLoad() {
      console.log("图片加载完成");
      if (this.isImageDownloading) {
        this.isImageDownloading = false;
        uni.showToast({ title: "图片下载并显示成功", icon: "success" });
      }
    },

    // 下载网络图片
    downloadNetworkImage() {
      // 检查网络
      uni.getNetworkType({
        success: (res) => {
          if (res.networkType === "none") {
            uni.showToast({ title: "无网络连接，无法下载", icon: "none" });
            return;
          }
          this.startDownload();
        }
      });
    },
    startDownload() {
      this.isImageDownloading = true;
      this.downloadProgress = 0;
      
      console.log(`开始下载网络图片：${this.networkImageUrl}`);
      uni.showToast({ title: "开始下载图片...", icon: "none" });

 
      this.downloadTask = uni.downloadFile({
        url: this.networkImageUrl,
        timeout: 30000, 
        success: (res) => {
          console.log("图片下载完成，返回结果：", res);
          

          if (res.statusCode === 200) {
           
            this.currentImage = res.tempFilePath;
            console.log("图片下载成功，临时路径：", res.tempFilePath);
            
            this.saveImageToAlbum(res.tempFilePath);
          } else {
            this.handleDownloadError(`下载失败，状态码：${res.statusCode}`);
          }
        },
        fail: (err) => {
          console.error("图片下载失败：", err);
          this.handleDownloadError(`下载失败：${err.errMsg}`);
        },
        complete: () => {
          console.log("下载任务完成（成功/失败）");
          this.downloadTask = null;
        }
      });

      // 监听下载进度
      this.downloadTask.onProgressUpdate((progress) => {
        this.downloadProgress = progress.progress;
        console.log(`下载进度更新：${progress.progress}%，已下载：${progress.totalBytesWritten}字节，总大小：${progress.totalBytesExpectedToWrite}字节`);
        
        // 进度日志详细输出
        if (progress.progress % 10 === 0) { // 每10%打印一次详细日志
          const downloadedMB = (progress.totalBytesWritten / 1024 / 1024).toFixed(2);
          const totalMB = (progress.totalBytesExpectedToWrite / 1024 / 1024).toFixed(2);
          console.log(`下载进度：${progress.progress}%，已下载：${downloadedMB}MB，总大小：${totalMB}MB`);
        }
      });
    },

    // 处理下载错误
    handleDownloadError(message) {
      this.isImageDownloading = false;
      this.downloadProgress = 0;
      this.downloadTask = null;
      
      console.error("下载错误：", message);
      uni.showToast({ title: message, icon: "none", duration: 2000 });
      this.currentImage = this.defaultImage;
    },

  


    getWeatherForecast() {
      uni.request({
        url: "http://t.weather.sojson.com/api/weather/city/101230501",
        method: "GET",
        timeout: 15000,
        header: {
          "Content-Type": "application/json"
        },
        success: (res) => {
          console.log("天气数据返回：", res);
          
          const result = res.data.data || res.data;
          
          if (result && result.forecast && result.forecast.length > 1) {
            const tomorrow = result.forecast[1];
            this.tomorrowWeather = {
              date: tomorrow.date || "未知",
              weekday: this.formatWeekday(tomorrow.weekday || tomorrow.week),
              high: (tomorrow.high || "").replace("高温", "").replace("℃", "").trim(),
              low: (tomorrow.low || "").replace("低温", "").replace("℃", "").trim()
            };
            this.weatherError = "";
            
            if (!this.tomorrowWeather.high || !this.tomorrowWeather.low) {
              this.weatherError = "天气数据不完整";
              this.tomorrowWeather = null;
            }
          } else {
            this.weatherError = "未获取到有效天气数据";
            console.error("天气数据格式错误：", res.data);
          }
        },
        fail: (err) => {
          console.error("天气数据获取失败：", err);
          if (err.errMsg.includes("timeout")) {
            this.weatherError = "请求超时，请检查网络";
          } else if (err.errMsg.includes("network")) {
            this.weatherError = "网络异常，请连接网络";
          } else if (err.errMsg.includes("ssl")) {
            this.weatherError = "SSL证书错误，建议使用HTTPS接口";
          } else {
            this.weatherError = "获取天气失败，错误：" + err.errMsg;
          }
        }
      });
    },


    formatWeekday(weekday) {
      if (!weekday) return "未知";
      const weekMap = {
        'Monday': '周一',
        'Mon': '周一',
        'Tuesday': '周二',
        'Tue': '周二',
        'Wednesday': '周三',
        'Wed': '周三',
        'Thursday': '周四',
        'Thu': '周四',
        'Friday': '周五',
        'Fri': '周五',
        'Saturday': '周六',
        'Sat': '周六',
        'Sunday': '周日',
        'Sun': '周日'
      };
      return weekMap[weekday] || weekday;
    }
  }
};
</script>

<style>

.weather-error {
  font-size: 16px;
  color: #ff4d4f;
  text-align: center;
  padding: 10px 0;
}


.download-progress {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 180px;
  text-align: center;
  z-index: 10;
}

.progress-text {
  font-size: 18px;
  color: #ffffff;
  text-shadow: 0 0 3px rgba(0,0,0,0.5);
  margin-bottom: 8px;
  font-weight: bold;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background-color: rgba(255,255,255,0.3);
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #1989fa;
  border-radius: 4px;
  transition: width 0.3s ease;
}

/* 其他原有样式保持不变 */
.container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.back-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 20px;
  color: #333;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 17px;
  font-weight: 500;
  color: #333;
}

.image-container {
  display: flex;
  justify-content: center;
  padding: 30px 0;
  background-color: #fff;
  position: relative; /* 为进度条定位做准备 */
}

.display-image {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #eee;
}

.button-group {
  padding: 20px 15px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.func-btn {
  height: 48px;
  line-height: 48px;
  font-size: 16px;
  color: #333;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.func-btn:disabled {
  color: #999;
  background-color: #f5f5f5;
}

.weather-container {
  padding: 20px 15px;
  background-color: #fff;
  margin: 15px;
  border-radius: 8px;
  border: 1px solid #eee;
}

.weather-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.weather-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
  font-size: 16px;
  color: #666;
}

.weather-loading {
  font-size: 16px;
  color: #999;
  text-align: center;
  padding: 10px 0;
}
</style>